package com.zhihuishu.micro.course.openapi.course.impl;

import com.zhihuishu.micro.course.dto.ChapterDto;
import com.zhihuishu.micro.course.openapi.course.CcCourseOpenService;
import com.zhihuishu.micro.course.openapi.course.CourseChapterOpenService;
import com.zhihuishu.micro.course.openapi.course.CourseLessonOpenService;
import com.zhihuishu.micro.course.openapi.course.CourseLessonVideoOpenService;
import com.zhihuishu.micro.course.openapi.course.dto.CourseChapterDto;
import com.zhihuishu.micro.course.openapi.course.dto.CourseLessonDto;
import com.zhihuishu.micro.course.openapi.course.dto.CourseLessonVideoDto;
import com.zhihuishu.micro.course.service.ChapterTreenityService;
import com.zhihuishu.remote.ErrorCode;
import com.zhihuishu.remote.RemoteException;
import com.zhihuishu.remote.RemoteResult;
import com.zhihuishu.toolkit.helper.BeanHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author Jiangli
 * @date 2016/10/17 15:27
 */
@Service("courseChapterOpenService")
public class CourseChapterOpenServiceImpl extends BaseOpenImpl implements CourseChapterOpenService {
    @Resource
    private ChapterTreenityService chapterAllService;//所有章 service
    @Resource
    private CourseLessonOpenService courseLessonOpenService;//节 open service
    @Resource
    private CourseLessonVideoOpenService courseLessonVideoOpenService;//小节 open service

    @Resource
    private CcCourseOpenService ccCourseOpenService;//用来清除章完整进度缓存


    private static final String moduleNameCN = "章";

    @Override
    public RemoteResult<CourseChapterDto> createByCourseId(CourseChapterDto courseChapterDto, long createUserId) throws RemoteException {
        RemoteResult<CourseChapterDto> result = new RemoteResult<CourseChapterDto>();
        try {
            ChapterDto dbDto = BeanHelper.transTo(courseChapterDto, ChapterDto.class);

            Integer newId = chapterAllService.create(dbDto, createUserId);
            dbDto.setId(newId);

            CourseChapterDto resultDto = BeanHelper.transTo(dbDto, CourseChapterDto.class);

            result.setSuccess(true);
            result.setResult(resultDto);
        } catch (Exception e) {
            log.error("保存-" + moduleNameCN + "-报错");
            throw new RemoteException(e).setMessage("保存-" + moduleNameCN + "-报错!");
        }

        return result;
    }

    @Override
    public RemoteResult<Void> updateByDto(CourseChapterDto chapter, long updateUserId) throws RemoteException {
        RemoteResult<Void> result=new RemoteResult<Void>();
        if(chapter==null){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
            return result;
        }
        try {
            ChapterDto chapterDto = BeanHelper.transTo(chapter, ChapterDto.class);
            chapterAllService.update(chapterDto,updateUserId);

            Integer isPass = chapterDto.getIsPass();
            Long courseId =chapterDto.getCourseId();
            //清除完整度百分比缓存
            if (isPass!=null&&courseId!= null) {
                ccCourseOpenService.delProgressByCourseId(courseId);
            }

            result.setSuccess(true);
        } catch (Exception e) {
            throw new RemoteException(e).setMessage("修改-" + moduleNameCN + "-出错!") ;
        }
        return result;
    }

    @Override
    public RemoteResult<Void> deleteById(Integer chapterId, long deleteUserId) throws RemoteException {
        RemoteResult<Void>  result = new RemoteResult<Void>();
        if(chapterId == null){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
            return result ;
        }
        try {
            chapterAllService.delete(chapterId,deleteUserId);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RemoteException(e).setMessage("删除-" + moduleNameCN + "-出错!") ;
        }
        return result;
    }

    @Override
    public RemoteResult<List<CourseChapterDto>> queryListByCourseId(long courseId) throws RemoteException {
        RemoteResult<List<CourseChapterDto>> result=new RemoteResult<List<CourseChapterDto>>();
        try {
            List<ChapterDto> chapterDtoList = chapterAllService.list(courseId);
            List<CourseChapterDto> courseOpenDtoList =  new ArrayList<CourseChapterDto>();
            if (!CollectionUtils.isEmpty(chapterDtoList)){
                for(ChapterDto course : chapterDtoList){
                    CourseChapterDto courseOpenDto = BeanHelper.transTo(course, CourseChapterDto.class);
                    courseOpenDtoList.add(courseOpenDto);
                }
            }
            result.setResult(courseOpenDtoList);
        } catch (Exception e) {
            result.setSuccess(false);
            throw new RemoteException(e).setMessage("查询-" + moduleNameCN + "列表-出错!") ;
        }
        return result;
    }

    @Override
    public RemoteResult<List<CourseChapterDto>> queryListByCourseIdNonLazy(long courseId) throws RemoteException {
        //courseId->List<CourseChapterDto>章数据
        RemoteResult<List<CourseChapterDto>> result=queryListByCourseId(courseId);

        try {
            //courseId->List<CourseLessonDto>节数据
            RemoteResult<List<CourseLessonDto>> lessonDtoRs = courseLessonOpenService.queryListByCourseId(courseId);
            //courseId->List<CourseLessonVideoDto>小节数据
            RemoteResult<List<CourseLessonVideoDto>> lessonVideoDtoRs = courseLessonVideoOpenService.queryListByCourseId(courseId);
            if (result.isSuccess() && lessonDtoRs.isSuccess() && lessonVideoDtoRs.isSuccess()) {
                List<CourseChapterDto> chapterDtoList = result.getResult();

                //<ChapterId,Index in ChapterDtoList>
                //10001234,0
                //10001235,1
                //10001236,2
                Map<String, Integer> chapterIdIndexMap = new HashMap<String, Integer>();
                for (int i = 0; i < chapterDtoList.size(); i++) {
                    CourseChapterDto one = chapterDtoList.get(i);
                    chapterIdIndexMap.put(String.valueOf(one.getId()),i);
                }

                //<LessonId,Index in LessonDtoList>
                //20001234,0
                //20001235,1
                //20001236,2
                List<CourseLessonDto> lessonDtoList = lessonDtoRs.getResult();
                Map<String, Integer> lessonIdIndexMap = new HashMap<String, Integer>();
                for (int i = 0; i < lessonDtoList.size(); i++) {
                    CourseLessonDto one = lessonDtoList.get(i);
                    lessonIdIndexMap.put(String.valueOf(one.getId()),i);

                    //add to Chapter
                    //通过Map-<ChapterId,Index in ChapterDtoList>
                    Integer chapterId = one.getChapterId();
                    Integer idx = chapterIdIndexMap.get(String.valueOf(chapterId));
                    if (idx != null) {
                        CourseChapterDto ownChapter = chapterDtoList.get(idx);
                        List<CourseLessonDto> lessonList = ownChapter.getLessonList();
                        if (lessonList == null) {
                            lessonList = new LinkedList<CourseLessonDto>();
                            ownChapter.setLessonList(lessonList);
                        }
                        lessonList.add(one);
                    }
                }

                List<CourseLessonVideoDto> lessonVideoDtoList = lessonVideoDtoRs.getResult();
                for (int i = 0; i < lessonVideoDtoList.size(); i++) {
                    CourseLessonVideoDto one = lessonVideoDtoList.get(i);

                    //add to Lesson
                    //通过Map-<LessonId,Index in LessonDtoList>
                    Long lessonId = one.getLessonId();
                    Integer idx = lessonIdIndexMap.get(String.valueOf(lessonId));
                    if (idx != null) {
                        CourseLessonDto ownLesson = lessonDtoList.get(idx);
                        List<CourseLessonVideoDto> lessonVideoList = ownLesson.getLessonVideoList();
                        if (lessonVideoList == null) {
                            lessonVideoList = new LinkedList<CourseLessonVideoDto>();
                            ownLesson.setLessonVideoList(lessonVideoList);
                        }
                        lessonVideoList.add(one);
                    }
                }

            }

        } catch (Exception e) {
            result.setSuccess(false);
            throw new RemoteException(e).setMessage("非延时-查询-" + moduleNameCN + "列表-出错!") ;
        }
        return result;
    }

    @Override
    public RemoteResult<Void> sortByDtoList(List<CourseChapterDto> chapterList, long updateUserId) throws RemoteException {
        RemoteResult<Void> result=new RemoteResult<Void>();
        if(CollectionUtils.isEmpty(chapterList)){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
            return result;
        }
        try {
            List<ChapterDto> dbDtoList = new LinkedList<ChapterDto>();
            for (CourseChapterDto courseChapterDto : chapterList) {
                dbDtoList.add(BeanHelper.transTo(courseChapterDto, ChapterDto.class));
            }

            chapterAllService.sort(dbDtoList,updateUserId);

            result.setSuccess(true);
        } catch (Exception e) {
            throw new RemoteException(e).setMessage("排序-" + moduleNameCN + "-出错!") ;
        }
        return result;
    }
}
